<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <div>
    <Spin :spinning="pageLoading" tip="加载中..." size="large" class="page-loading-wrapper">
      <div class="lg:flex !mt-4 main-content-container" :class="{ 'loading-content': pageLoading }">
      <div class="lg:w-4/10 enter-y !mr-4">
        <BasicTable @register="registerTable" @edit-change="rowChange">
          <template #tableTitle>
            <div style="display: flex; align-items: center">
              <Icon :icon="getTitle.icon" class="m-1 pr-1" />
              <span class="mr-2"> 商品列表 </span>
            </div>
          </template>
          <template #toolbar>
            <a-button type="default" @click="handleAdd">
              <!-- <EyeOutlined /> -->
               <!-- <PlusOutlined /> -->
              <Icon icon="i-ant-design:plus-outlined" /> {{ t('新建标签') }}
            </a-button>
          </template>
        </BasicTable>
      </div>
      <!-- :tableDataLength="tableDataLength" -->
      <div class="lg:w-6/10 enter-y">
        <printForm
          @selectLabel="handleSelectLabel"
          :rdOrderPrintList="rdOrderPrintList"
          :rdOrdeData="rdOrdeData"
          @deleteItem="handleDeleteItem"
          @restoreData="handleRestoreData"
          @clearTableSelection="clearTableSelection"
          @addItemsToTable="addItemsToTable"
          @getTableLength="getTableLength"
          @update-card-data="handleUpdateCardData"
          @updateLogisticsInfo="handleUpdateLogisticsInfo"
          @updateShdw="handleUpdateShdw"
        />
      </div>
      </div>
    </Spin>

    <!-- 拆分组件 -->
    <SplitModal ref="splitModalRef" @splitSuccess="handleSplitSuccess" />
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsWmsRdOrderRdOrderPrinfxEdit',
  });
</script>
<script lang="ts" setup>
  import { unref, onMounted, computed, ref, defineComponent, nextTick } from 'vue';
  import {
    TreeSelect,
    Menu,
    Dropdown,
    TableSummary,
    TableSummaryCell,
    TableSummaryRow,
    Spin
  } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  // import { puOrderPreDataDelete, puOrderPreDataPushAsn } from '/@/api/srm/asn/presh/puOrderPreData';
  import { FormProps } from '/@/components/Form';

  import { NumEnum } from '/@/enums/defEnum';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { useUserStore } from '/@/store/modules/user';
  import { getPrintFx } from '/@/api/wms/rd/order/rdOrder';
  import { jhPickDetailsbachSave } from '/@/api/wms/jh/pick/jhPickDetailsInv';
  import printForm from './printForm.vue';
  import SplitModal from './components/SplitModal.vue';
  import { useQuery } from '/@/hooks/web/usePage';

  const { hasPermission } = usePermission();
  const userStore = useUserStore();
  const getQuery = useQuery();
  // getQuery.value.printId

  const { t } = useI18n('rd.rd32.rdrecord32');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);

  // 存储选中的标签数据
  const selectedLabelData = ref([]);
  const rdOrderPrintList = ref([]);
  const rdOrdeData = ref(null);

  // 页面加载状态
  const pageLoading = ref(false);

  // 拆分组件引用
  const splitModalRef = ref();



  const getTitle = {
    icon: meta.icon || 'i-ant-design:book-outlined',
    // value: meta.title || t('订单变更记录'),
  };

  const searchForm: FormProps = {
    baseColProps: { lg: 8, md: 8 },
    labelWidth: 90,
    // showResetButton:false,
    schemas: [
      {
        label: t('发货单号'),
        field: 'fbillno',
        component: 'Input',
      },
    ],
  };
  const tableColumns: BasicColumn[] = [
    {
      title: t('商品名称'),
      dataIndex: 'basInv.invName',
      key: 'inv.invName',
      // sorter: true,
      width: 120,
      align: 'center',
    },
    {
      title: t('数量'),
      dataIndex: 'iqty',
      key: 'a.iqty',
      sorter: true,
      width: 40,
      align: 'left',
      showSummary: true,
    },
    {
      title: t('邮发代号'),
      dataIndex: 'basInv.yfdh',
      key: 'inv.yfdh',
      sorter: true,
      width: 50,
      align: 'left',
    },
  ];
  const actionColumn: BasicColumn = {
    width: 50,
    actions: (record: Recordable) => [
      {
        // label: t('添加到标签'),
        icon: 'i-ant-design:plus-outlined',
        fontSize: 18,
        onClick: handleForm.bind(this, record),
        // auth: 'jh:plan:jhPlanArea:edit',
      },
      {
        label: t('拆分'),
        onClick: handleSplit.bind(this, record),
        // auth: 'jh:plan:jhPlanArea:edit',
      },
    ],
  };

  const [
    registerTable,
    { reload, getForm, getDataSource, getSelectRows, setSelectedRowKeys, setProps, setTableData },
  ] = useTable({
    beforeFetch: (params) => {
      // params.companyCode = companyData.value.code || '-1';
      return params;
    },
    columns: tableColumns,
    actionColumn: actionColumn,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: false,
    showSearchForm: false,
    canResize: true,
    indexColumnProps: {
      width: 30,
    },
    tableSetting: {
      redo: false,
    },
    tableSettingStoreKey: 'registerTable',
    rowSelection: {
      type: 'checkbox',
      columnWidth: 20,
    },
    pagination: false,
    immediate: false,
    ellipsis: false,
    showCustomSummary: true,
  });
  // 定义传递给子组件的方法
  const addDataToRdOrderRdsList = (data) => {
    if (selectedLabelData.value) {
      selectedLabelData.value[0]['rdOrdersPrintList'].push(data);
    }
  };
  async function handleForm(record: Recordable) {
    console.log('handleForm', selectedLabelData.value);
    if (selectedLabelData.value && selectedLabelData.value.length !== 1) {
      showMessage(t('请先选择一个标签'), 'error');
      return;
    }
    // 调用子组件方法添加数据
    addDataToRdOrderRdsList(record);
    // 并且从移除当前这条数据
    const newData = getDataSource().filter((item) => item.id !== record.id);
    setTableData(newData);
  }

  async function handleSplit(record: Recordable) {
    // 调用子组件的拆分方法
    if (splitModalRef.value) {
      splitModalRef.value.openSplit(record);
    }
  }

  // 处理拆分成功事件
  function handleSplitSuccess(data: { originalRecord: any; newRecords: any[] }) {
    console.log('接收到拆分成功事件:', data);

    const { originalRecord, newRecords } = data;

    // 获取当前表格数据
    const currentData = getDataSource();

    // 严格移除原始记录（确保完全移除，避免残留）
    const updatedData = currentData.filter(item => {
      // 严格比较ID，确保原始记录被完全移除
      const isOriginalRecord = item.id === originalRecord.id;
      if (isOriginalRecord) {
        console.log('移除原始记录:', item.id);
      }
      return !isOriginalRecord;
    });

    // 添加新的拆分记录
    updatedData.push(...newRecords);

    // 更新表格数据
    setTableData(updatedData);

    // 清除表格选中状态，避免选中状态混乱
    clearTableSelection();

    // 记录拆分操作，用于后续数据处理
    console.log('拆分操作记录:', {
      originalId: originalRecord.id,
      newRecordIds: newRecords.map(record => record.id),
      splitTimestamp: Date.now(),
      removedOriginal: true,
      addedNewRecords: newRecords.length
    });

    console.log('表格数据已更新');
    console.log('原始记录已移除:', originalRecord.id);
    console.log('新记录已添加:', newRecords.map(r => r.id));
    console.log('当前表格数据总数:', updatedData.length);
  }

  async function rowChange({ column, value, record }) {
    // let { editValueRefs: { ntotalnum } } = record;
    // if (value > record.nversion) {
    //   showMessage('本次送货数不能超过剩余数！');
    //   ntotalnum.value = record.nversion
    // }
    let {
      editValueRefs: { selQty },
    } = record;
    selQty.value = value.toFixed(NumEnum.scaleSelQty);
  }

  const handleSelectLabel = (selectedItem) => {
    console.log('接收到选中的标签数据1:', selectedItem);
    selectedLabelData.value = selectedItem;
  };

  async function handleGetPrintFx() {
    try {
      pageLoading.value = true;
      console.log('开始获取打印数据，显示loading...');

      // 添加最小loading时间，确保用户能看到loading效果
      const [res] = await Promise.all([
        getPrintFx({ printId: getQuery.value.printId }),
        new Promise(resolve => setTimeout(resolve, 500)) // 最小500ms loading时间
      ]);

      console.log('获取打印数据成功:', res);
      setTableData(res.data.rdOrdersPrintList || []);
      // 把数据传递给子组件 res.data.rdOrderPrintList
      rdOrderPrintList.value = res.data.rdOrderPrintList || [];
      rdOrdeData.value = res.data;

      console.log('数据设置完成，隐藏loading...');
    } catch (error) {
      console.error('获取打印数据失败:', error);
      showMessage('获取打印数据失败，请重试', 'error');
    } finally {
      pageLoading.value = false;
    }
  }

  handleGetPrintFx();

  async function handleAdd() {
    try {
      pageLoading.value = true;
      console.log('开始新建标签，显示loading...');

      let arr = await getSelectRows();
      if (arr.length == 0) {
        showMessage(t('请先选择商品'));
        return;
      }

      console.log('选中的商品:', arr);

      // 添加最小loading时间，确保用户能看到loading效果
      await new Promise(resolve => setTimeout(resolve, 300));

      // 获取当前选中的商品数据（这些就是要添加到标签中的数据）
      const selectedRowsData = await getSelectRows();
      console.log('当前选中的商品数据:', selectedRowsData);

      // 验证选中的数据，确保只包含有效的记录
      const validSelectedData = selectedRowsData.filter((item: any) => {
        // 检查记录是否有效
        if (!item || !item.id) {
          console.warn('发现无效记录，已过滤:', item);
          return false;
        }
        return true;
      });

      console.log('有效的选中数据:', validSelectedData);
      console.log('过滤后的数据数量:', validSelectedData.length);

      const data = {
        address: rdOrdeData.value.address || '',
        iqty: rdOrdeData.value.iqty || '',
        shr: rdOrdeData.value.fperson || '',
        phone: rdOrdeData.value.fphone || '',
        shdw: rdOrdeData.value.shdw || '',
        rdOrdersPrintList: validSelectedData, // 使用验证后的数据
      };
      rdOrderPrintList.value.push(data);

      // 勾选的数据从表格中移除（使用有效数据的ID）
      const selectedIds = validSelectedData.map((item: any) => item.id);
      console.log('要移除的记录ID:', selectedIds);

      // 使用选中记录的 id 数组来过滤数据
      const currentTableData = getDataSource();
      const newData = currentTableData.filter((item: any) => {
        const shouldRemove = selectedIds.includes(item.id);
        if (shouldRemove) {
          console.log('从表格中移除记录:', item.id);
        }
        return !shouldRemove;
      });

      console.log('表格数据更新前数量:', currentTableData.length);
      console.log('表格数据更新后数量:', newData.length);

      setTableData(newData);
      clearTableSelection();
      showMessage('新建标签成功');

      console.log('新建标签完成，隐藏loading...');
    } catch (error) {
      console.error('新建标签失败:', error);
      showMessage('新建标签失败，请重试', 'error');
    } finally {
      pageLoading.value = false;
    }
  }
  const handleDeleteItem = (index: number) => {
    rdOrderPrintList.value.splice(index, 1);
  };
  const handleRestoreData = (data: Recordable) => {
    const currentData = getDataSource();
    currentData.push(data);
    setTableData(currentData);
  };

  const clearTableSelection = () => {
    // 清空表格的选中状态
    setSelectedRowKeys([]);
  };

  const addItemsToTable = (items: Recordable[]) => {
    const currentData = getDataSource();
    const newData = [...currentData, ...items];
    setTableData(newData);
  };

  const handleUpdateCardData = ({ cardIndex, newRdOrdersPrintList, shouldDeleteCard }) => {
    if (shouldDeleteCard) {
      // 如果需要删除整个卡片
      rdOrderPrintList.value.splice(cardIndex, 1);
    } else {
      // 只更新卡片内的数据
      rdOrderPrintList.value[cardIndex].rdOrdersPrintList = newRdOrdersPrintList;
    }
  };

  // 处理物流信息更新事件
  const handleUpdateLogisticsInfo = (formValues) => {
    console.log('接收到物流信息更新:', formValues);

    // 更新 rdOrdeData 的数据
    rdOrdeData.value = {
      ...rdOrdeData.value,
      ...formValues,
      fperson: formValues.shr,
      fphone: formValues.phone,
      address: formValues.address,
    };

    // 更新 rdOrderPrintList 的数据
    rdOrderPrintList.value = rdOrderPrintList.value.map((item) => ({
      ...item,
      ...formValues,
    }));

    console.log('更新后的 rdOrderPrintList:', rdOrderPrintList.value);
    console.log('更新后的 rdOrdeData:', rdOrdeData.value);
  };

  // 处理收货单位批改事件
  const handleUpdateShdw = (updateData) => {
    console.log('接收到收货单位批改:', updateData);

    const { selectedIndexes, shdw } = updateData;

    // 更新选中标签的收货单位
    selectedIndexes.forEach((index) => {
      if (rdOrderPrintList.value[index]) {
        rdOrderPrintList.value[index] = {
          ...rdOrderPrintList.value[index],
          shdw: shdw,
        };
      }
    });

    console.log('更新后的 rdOrderPrintList:', rdOrderPrintList.value);
    showMessage(`成功批改 ${selectedIndexes.length} 个标签的收货单位为：${shdw}`);
  };

  // const tableDataLength = computed(() => {
  //   if (!getDataSource()) {
  //     return 0;
  //   }
  //   return getDataSource().length;
  // });

  onMounted(async () => {
    try {
      pageLoading.value = true;
      console.log('页面开始加载，显示loading...');

      // 添加最小loading时间，确保用户能看到loading效果
      const [, ] = await Promise.all([
        (async () => {
          setProps();
          await reload();
        })(),
        new Promise(resolve => setTimeout(resolve, 800)) // 最小800ms loading时间
      ]);

      console.log('页面加载完成，隐藏loading...');
    } catch (error) {
      console.error('页面加载失败:', error);
      showMessage('页面加载失败，请重试', 'error');
    } finally {
      pageLoading.value = false;
    }
  });

  const checkTableLength = () => {
    return getDataSource().length;
  };

  // 新增方法，接收回调函数
  const getTableLength = (callback: (length: number) => void) => {
    const length = checkTableLength();
    callback(length);
  };

</script>
<style scoped>
  :deep(.jeesite-editable-cell__action) {
    display: none;
  }

  :deep(.edit-cell-align-center) {
    width: 100% !important;
  }

  .main-content-container {
    height: calc(100vh - 120px); /* 减去头部和其他元素的高度 */
    overflow: hidden; /* 防止整体页面滚动 */
  }

  /* 使用 :deep() 来穿透样式 */
  .main-content-container :deep(.lg\:w-4\/10) {
    height: 100%;
    overflow: hidden;
  }

  .main-content-container :deep(.lg\:w-6\/10) {
    height: 100%;
    overflow: hidden;
  }

  .title1 {
    width: 100%;
    min-height: calc(100vh - 120px);
    display: flex;
    flex-direction: column;
    /* background: #ffffff;
    padding: 20px;
    display: flex;
    justify-content: center;
    align-items: center; */
  }

  /* Loading 样式优化 */
  .page-loading-wrapper {
    min-height: 400px;
    position: relative;
  }

  .page-loading-wrapper :deep(.ant-spin-container) {
    position: relative;
    transition: opacity 0.3s;
  }

  .page-loading-wrapper :deep(.ant-spin-spinning .ant-spin-container) {
    opacity: 0.5;
    pointer-events: none;
  }

  .page-loading-wrapper :deep(.ant-spin) {
    max-height: none;
  }

  .page-loading-wrapper :deep(.ant-spin-dot) {
    font-size: 24px;
  }

  .page-loading-wrapper :deep(.ant-spin-text) {
    color: #1890ff;
    font-size: 16px;
    margin-top: 12px;
  }

  .loading-content {
    transition: all 0.3s ease;
  }

  .loading-content.loading {
    filter: blur(1px);
    opacity: 0.7;
  }
</style>
